<?php
/*
*	Kleophatra - Open Source Content Management System
*	------------------------------------------------------------------------
*	Copyright (C) 2007-2009, Sergio Milardovich <smilardovich@yahoo.com.ar>
*	This program is Free Software.
*	Kleophatra validation library
*
*	@package	Kleophatra
*	@subpackage	/lib
*	@license	http://www.gnu.org/copyleft/gpl.html GNU/GPL License 2.0
*	@author		Sergio Milardovich <smilardovich@yahoo.com.ar>
*	@link		http://www.kleophatra.org
*/
class kleovalidate {
  var $validate;
  var $default_validation_error = 'ERROR!';

  function do_validation(&$output_error=array()){
    foreach($this->validate as $field => $attributes){

      if($attributes['message']){
	$error_message = $attributes['message'];
      } else {
	$error_message = $this->default_validation_error;
      }

      if($attributes['rule']){
	switch($attributes['rule']){
	  case 'numeric':
	    if(!is_numeric($field)){
	      $error = true;
	    }
	  break;
	  case 'string':
	    if(!is_string($field)){
	      $error = true;
	    }
	  break;
	  case 'email':
	    if(preg_match("/^[a-zA-Z0-9\.\-\_]*@[a-zA-Z0-9\.\-\_]*$/", $field, $matches)){
	      $error = true;
	    }
	  break;
	  case 'web':
	    if(preg_match("/^(?:http:\/\/)?((?:[\w\-]+(?:\.[\w^_]+)+){1}\S*)$/", $field, $matches)){
	      return true;
	    }
	  break;
	}
      }

      if($attributes['empty'] == false){
	if(empty($field)){
	  $error = true;
	}
      }

      if($attributes['maxlength']){
	if(strlen($field) > $attributes['maxlength']){
	  $error = true;
	}
      }

      if($attributes['minlength']){
	if(strlen($field) < $attributes['minlength']){
	  $error = true;
	}
      }

      if(isset($error)){
	$output_error[]['message'] = $error_message;
      }


    }
  }
  function run_tests(&$output_error){
    $field = '12345';
    $other_field = '12345asdf';
    $this->validate = array(
      $other_field => array(
	'rule' => 'string',
	'message' => 'Error!',
	'minlength' => 13
      ),
      'field' => array(
	'rule' => 'numeric',
	'message' => 'Error2!',
	'minlength' => 13
      )
    );
    $this->do_validation($output_error);
  }
}
?>